<template>
  <div class="tag-wrapper">
    <template v-if="tagList.length">
      <div class="tag-item" v-for="(item, index) in tagList" :key="index">
        <span>{{ item }}</span>
        <i v-if="closeable" class="iconfont icon-close" @click="closeTagClick(item)"></i>
      </div>
    </template>
    <div class="tag-add_input" v-show="isShowInput">
      <input
        type="text"
        @keyup.enter="inputAdd"
        v-model="inputValue"
        ref="inputRef"
        @blur="inputBlur"
      />
    </div>
    <div class="tag-add tag-item" v-if="isAdd" @click="addTagClick">
      <i class="iconfont icon-add"></i>
      <span>添加标签</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    closeable: {
      type: Boolean,
      default: () => false
    },
    isAdd: {
      type: Boolean,
      default: () => false
    },
    value: {
      type: [Array, String],
      default: () => []
    }
  },
  data() {
    return {
      tagList: [],
      inputValue: '',
      isShowInput: false
    }
  },
  methods: {
    // 添加标签
    addTagClick() {
      this.isShowInput = true
      this.$nextTick(() => {
        this.$refs.inputRef.focus()
      })
    },

    // 关闭标签
    closeTagClick(item) {
      this.tagList.splice(
        this.tagList.findIndex(ele => item === ele),
        1
      )
    },

    // 输入框enter
    inputAdd() {
      if (this.inputValue) {
        this.tagList.push(this.inputValue)
      }
      this.isShowInput = false
      this.inputValue = ''
    },

    // 输入框失去焦点
    inputBlur() {
      this.inputAdd()
    }
  },
  watch: {
    tagList: function(val) {
      this.$emit('on-change', val)
    }
  },
  created() {
    this.tagList = Array.isArray(this.value) ? this.value : this.value.split(',')
  }
}
</script>

<style lang="scss" scoped>
.tag-wrapper {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .tag-item {
    height: 24px;
    line-height: 24px;
    font-size: 12px;
    padding: 0 4px;
    margin: 0 4px;
    background: #f7f7f7;
    border: 1px solid #e8eaec;
    border-radius: 4px;
    i {
      font-size: 12px;
    }
  }
  .tag-add_input {
    margin: 0 4px;
    height: 24px;
    line-height: 24px;
    input {
      height: 24px;
      width: 100px;
      border: 1px solid #ccc;
      padding: 0 4px;
      color: #ccc;
    }
  }
  .tag-add {
    cursor: pointer;
    user-select: none;
    transition: 0.5s;
  }
  .tag-add:hover {
    border: 1px solid #409eff;
    color: #409eff;
  }
}
</style>
